package com.luyi.consumer.order.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 卢意
 * @create 2020-10-24 16:33
 */
@Component
public class MyLB implements LoadBalance{
	// 原子类  线程安全
	private AtomicInteger atomicInteger= new AtomicInteger(0);

	//
	public final int getAndIncrement(){
		int current;//初始值为0
		int next;//初始值为0
		do{//类似自旋锁   并发情况下访问次数可能会冲突
			current=this.atomicInteger.get();
			next=current >= 2147483647 ? 0: current +1; //current的值是否超过Integer的最大整形
		}while (!this.atomicInteger.compareAndSet(current, next));
		System.out.println("_______第几次次访问次数next="+next);
		return next;
	}
	@Override
	public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
		//第几次访问%主机数
		int index=getAndIncrement() % serviceInstances.size();
		//返回服务器实例列表的下标为index的服务器实例
		return serviceInstances.get(index);
	}
}
